package com.juyu.miliao.api.controller.wx;

import com.juyu.miliao.api.domain.dto.WxBindingDTO;
import com.juyu.miliao.api.domain.vo.WxUserInfoVo;
import com.juyu.miliao.api.service.WxBindingService;
import com.juyu.miliao.api.service.WxUserInfoService;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.VerifyUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信公众号绑定
 *
 * @author xuanqicheng
 * @create 2019-27-12:33
 */
@RestController
@RequestMapping("/wxBind")
@CrossOrigin
public class WxBindingController {

    private String phoneRegex="^[0-9]{11}$";

    @Autowired
    private WxBindingService wxBindingService;

    @Autowired
    private WxUserInfoService wxUserInfoService;
    /**
     * 发送验证码
     */
    @PostMapping("/code/phone")
    public void sendPhoneNumVerificationCode(HttpServletRequest request, @RequestBody WxBindingDTO wxBindingDTO){
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        if(wxBindingDTO.getPhone() == null || !wxBindingDTO.getPhone().matches(phoneRegex)) {
            throw new ConsumeRuntimeException("手机号格式不正确");
        }

        //生成验证码
        String verificationCode =  (int)((Math.random()*9+1)*1000)+"";
        /**
         * 存入redis
         */
        wxBindingService.sendPhoneNumValidateCode(wxBindingDTO.getPhone(),verificationCode,com);
    }

    @PostMapping("/index")
    public Object getWxBinding(@RequestBody @Validated WxBindingDTO wxBindingDTO, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            throw  new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        WxUserInfoVo wxUserInfo =wxUserInfoService.getWxUserInfo(wxBindingDTO.getOpenid());
        if(wxUserInfo.getSubscribe()!=1){
            throw  new ConsumeRuntimeException("未关注过公众号，请先关注！");
        }
        return wxBindingService.getWxBinding(wxBindingDTO);
    }

    /**
     * 领取金币
     * @param wxBindingDTO，领取金币秘钥
     * @return
     */
    @PostMapping("/gold")
    public Object getGold(@RequestBody WxBindingDTO wxBindingDTO ){

        if(StringUtils.isBlank(wxBindingDTO.getSecret())){

            throw  new ConsumeRuntimeException("参数不正确");
        }
        return wxBindingService.getGoldBySecret(wxBindingDTO.getSecret());
    }
}
